var ConnectEquipmentTableInit = function(){
	var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        	$('#connectEquipmentTable').bootstrapTable({
            url: ctx +'/equipment/connect/listEquipmentConnectByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop:false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect:false,                    //禁止多选
            checkboxHeader:true,                 //列头取消多选
            columns: [
            {
            	checkbox:true,
            	align : 'center',
                valign : 'middle',
            },
            {
            	title: '序号',
            	align : 'center',
                valign : 'middle',
                formatter : function (value, row, index){
                	var options = $('#connectEquipmentTable').bootstrapTable('getOptions');  
                    return options.pageSize * (options.pageNumber - 1) + index + 1;  
                }
            },
            {
                field: 'clientCode',
                title: '采集终端编号',
                sortable:false,
                align : 'center',
                valign : 'middle',
                
            }, {
                field: 'clientName',
                title: '采集终端名称',
                sortable:false,
                align : 'center',
                valign : 'middle',
            }, {
                field: 'equipCode',
                title: '连接设备编号',
                sortable:false,
                align : 'center',
                valign : 'middle',
            }, {
                field: 'equipName',
                title: '连接设备名称',
                sortable:false,
                align : 'center',
                valign : 'middle',
            }, {
                field: 'operationName',
                title: '所属工序',
                sortable:false,
                align : 'center',
                valign : 'middle',
            },{
                field: 'communicateAddr',
                title: '数据源地址',
                sortable:false,
                align : 'center',
                valign : 'middle',
            }, {
                field: 'type',
                title: '采集方式',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter:function(value, row, index){
                	if(value=="1"){
                		return "PLC";
                	}
                	if(value=="2"){
                		return "文件";
                	}
                	if(value=="3"){
                		return "数据库";
                	}
                	if(value=="4"){
                		return "上位机";
                	}
                }
            },
            //     {
            //     field: 'frequency',
            //     title: '采集频率',
            //     sortable:false,
            //     align : 'center',
            //     valign : 'middle',
            //     formatter: function(value, row, index){
            //     	return value+"秒";
            //     }
            // },
                {
                field: 'equipRemark',                
                title: '备注',
                sortable:false,
                align : 'center',
                valign : 'middle',
                formatter: function(value, row, index){
                	var html ="<p class='click_btn' style='overflow: hidden; white-space: nowrap; text-overflow: ellipsis;width:150px;margin-left:auto;margin-right:auto;' >"+value+"</p>";
                	return html;
                }
            }],

        });
    };	
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        	size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
        	sort: params.sort,
        	order: params.order,
        	clientCode: $("#clientCodeConnected").val(),
        	operationId: $(".operationSearch").val(),
        	equipCode: $("#connectEquipCode").val(),
        	equipName: $("#connectEquipName").val(),
        };
        return temp;
    };
    return oTableInit;       
};

var ConnectEquipmentInit =function(){
	return {
		init:function(){
			ConnectEquipmentInit.query();
			ConnectEquipmentInit.keyQuery();
			ConnectEquipmentInit.reset();
			ConnectEquipmentInit.refresh();
			ConnectEquipmentInit.del();
			ConnectEquipmentInit.add();
			ConnectEquipmentInit.update();
			ConnectEquipmentInit.validatorForm();
			ConnectEquipmentInit.changeCollect();
			SystemCommon.getQueryOperation();
			ConnectEquipmentInit.changeEquipment();
		},
		//条件查询
		query : function(){
			$("#queryConnectEquipment").on("click","",function(){
				$('#connectEquipmentTable').bootstrapTable('refreshOptions',{
					pageNumber:1,
				});
			});
		},
		//按键触发查询
		keyQuery : function(){
			$(".queryConnectEquipment").keypress(function (e) {
	            if (e.which == 13) {
	                $("#queryConnectEquipment").trigger("click");
	            }
	        });
		},
		//重置功能
		reset : function() {
			$("#resetConnectEquipment").on("click","",function(){
				$(".clearfix input").val("");
				$("#connectOperation").each(function(){
					$("#connectOperation").empty();
					$("#connectOperation").append("<option value=''></option>");
					$('#connectOperation').trigger('change.select2');
				});
			});
		},
		refresh : function(){
			//刷新
			$("#refreshConnectEquipment").on("click",function(){
				$('#connectEquipmentTable').bootstrapTable('refresh');
			});
		},
		//删除设备类别
		del : function(){
			/**
			 * 删除功能
			 */
			$("#delConnectEquipment").on("click","",function(){
				var pkIds=new Array();
			    $.map($('#connectEquipmentTable').bootstrapTable('getSelections'), function (row) {
			    	
			        return pkIds.push(row.pkId);
			    });
			    if (pkIds.length <= 0 ) {
			    	DialogUtil.ok("请选择需要操作的记录");
			        return;
			    }
			    
			    
			    DialogUtil.ok_and_cancel("是否删除?",function(){
			    	
			    	$.ajax({
						url: ctx + '/equipment/connect/delEquipmentConnect/del.mvc',
					    type:"post", 
					    dataType:'json',
					    data : {pkIds:JSON.stringify(pkIds)},
					    success : function(response){
					    	console.log(response);
					    	if (response.result == true) {
					    		DialogUtil.warning("删除成功");
					    		$('#connectEquipmentTable').bootstrapTable('refresh');
					    	}
					    },
					    error: function(XMLHttpRequest, textStatus, errorThrown){
					    	DialogUtil.warning("系统错误");
					    }
					});
			    },function(){});
			});
		},
		//校验表单
		validatorForm : function(){
			$(".connectEquipmentForm").bootstrapValidator({
				message: 'This value is not valid',
	            live: 'submitted',
	            fields: {/*验证*/
	            	clientId: {
	                    message: '采集终端编号无效',
	                    validators: {
	                        notEmpty: {
	                            message: '请选择采集终端编号'
	                        },
	                    }
	                },
	                clientName: {
	                    message: '采集终端名称无效',
	                    validators: {
	                        notEmpty: {
	                            message: '采集终端名称不能为空'
	                        },
	                    }
	                },
	                equipCode: {
	                    message: '连接设备编号无效',
	                    validators: {
	                        notEmpty: {
	                            message: '请选择连接设备编号'
	                        },
	                    }
	                },
	                equipName: {
	                    message: '连接设备名称无效',
	                    validators: {
	                        notEmpty: {
	                            message: '连接设备名称不能为空'
	                        },
	                    }
	                },
	                communicateAddr: {
	                    message: '设备通信地址无效',
	                    validators: {
	                        notEmpty: {
	                            message: '设备通信地址不能为空'
	                        },
	                        stringLength: {
	                            max: 20,
	                            message: '设备通信地址不能超过20个字符'
	                        }
	                    }
	                },
	                communicateInter: {
	                    message: '接口无效',
	                    validators: {
	                        notEmpty: {
	                            message: '接口不能为空'
	                        },
	                    }
	                },
	                address: {
	                    message: '数据源地址无效',
	                    validators: {
	                        notEmpty: {
	                            message: '请填写数据源地址'
	                        },
	                        stringLength: {
	                            max: 20,
	                            message: '数据源地址不能超过20个字符'
	                        }
	                    }
	                },
	              
	                frequency: {
	                    message: '采集频率无效',
	                    validators: {
	                        notEmpty: {
	                            message: '采集频率不能为空'
	                        },
	                        regexp: {
	                            regexp: /^[1-9]*[1-9][0-9]*$/,
	                            message: '采集频率为正整数'
	                        },
	                        stringLength: {
	                            max: 10,
	                            message: '采集频率不能超过10个字符'
	                        }
	                    }
	                },
                    remark: {
                        message: '备注无效',
                        validators: {
                            stringLength: {
                                max: 20,
                                message: '备注不能超过20个字符'
                            }
                        }
                    }
	            }
			});
			
			//模态框消失清空信息
			$(".connectEquipmentForm").on("hidden.bs.modal",function(e){
				debugger;
				$('.connectEquipmentForm input').each(function() {
					if ($(this).val() != "" || $(this).prop('checked') == true) {
						$(this).val("").prop('checked', false);
					}
				});
				$('.connectEquipmentForm').each(function(){
					$(this).data('bootstrapValidator').destroy();
				})
				ConnectEquipmentInit.validatorForm();
				$("#myModal .clientCodeConnect").removeAttr("disabled");
				$("#myModal .equipCodeConnect").removeAttr("disabled");
				$('#myModal .clientCodeConnect').empty();
				$("#myModal .clientCodeConnect").append('<option value="">请选择</option>');
				$('#myModal .equipCodeConnect').empty();
				$("#myModal .equipCodeConnect").append('<option value="">请选择</option>');
				
			});
			
			$("#myModal").on("change",".type",function(){
				
				$("#myModal input[name='address']").attr("disabled",false);
				$("#myModal input[name='frequency']").attr("disabled",false);
				
				//采集方式变更
				if($("#myModal .type").val()=='4'){//上位机
					$("#myModal input[name='address']").attr("disabled",true);
					$("#myModal input[name='frequency']").attr("disabled",true);
				}else if($("#myModal .type").val()=='2'){
					$("#myModal input[name='frequency']").attr("disabled",true);
				}else{
					$("#myModal input[name='frequency']").attr("disabled",false);
					$("#myModal input[name='address']").attr("disabled",false);
				}
			});
			
		
		},
		//新增用户
		add : function(){
			//新增用户
			$("#addConnectEquipment").on("click",function(){
				$('#myModal .modal-title').html("新增");
				$('#myModal').modal();
				$.fn.modal.Constructor.prototype.enforceFocus = function() { 
					 $("#myModal select[name='clientCode']").focus();
				}; 
				$("#myModal input[name='clientName']").attr("disabled",true);
				$("#myModal input[name='operationName']").attr("disabled",true);
				$("#myModal input[name='equipName']").attr("disabled",true);
				$("#myModal input[name='communicateInter']").attr("disabled",true);
				$("#myModal .yes").attr("disabled",false);
//				ConnectEquipmentInit.getQueryEquipment();
				ConnectEquipmentInit.getCollect();
			});
			//新增用户-确定
			$("#myModal .yes").on(
					"click",
					function() {
//						$("#myModal input[name='clientName']").attr("disabled",false);
//						$("#myModal input[name='operationName']").attr("disabled",false);
//						$("#myModal input[name='equipName']").attr("disabled",false);
//						$("#myModal input[name='communicateInter']").attr("disabled",false);
						$("#myModal").data("bootstrapValidator").validate();
						var flag = $("#myModal").data("bootstrapValidator").isValid();
						if(!flag){
							//未通过验证
							return false;
						}
						
						$("#myModal .clientCodeConnect").removeAttr("disabled");
						$("#myModal .equipCodeConnect").removeAttr("disabled");
						if ($('.equipCodeConnect').select2('val') != null) {
							$("#myModal input[name='equipCode']").val($('.equipCodeConnect').select2('val'));
						}
						//$("#myModal .yes").attr("disabled",true);
						$.ajax({
							url : ctx + '/equipment/connect/saveEquipmentConnect/save.mvc',
							type : "post",
							dataType : 'json',
							data : $("#defaultForm").serialize(),
							success : function(response) {
								if (response.result == true) {
									DialogUtil.ok("保存成功");
									//取消
									$('#myModal').modal('hide');
									$('#connectEquipmentTable').bootstrapTable('refresh');
								}
								if (response.result == false ) {
									DialogUtil.warning(response.message);
								//	$("#myModal .yes").attr("disabled",false);
								}
								
							},
							error : function(XMLHttpRequest, textStatus, errorThrown) {
								alert("系统错误");
							}
						});
						return false;
						
					});
		},
		//修改用户
		update : function(){
			//修改用户
			$("#updateConnectEquipment").on("click",function(){
				$('#myModalUpdate .modal-title').html("修改");
				var ids = $.map($('#connectEquipmentTable').bootstrapTable('getSelections'), function (row) {
 				return row.pkId;
			    });
				if (ids.length != 1 ) {
			    	DialogUtil.warning("请选择一行修改");
			        return;
			    }
				
				$.ajax({
					url: ctx +'/equipment/connect/getEquipmentCollectById/get.mvc',
				    type:"post", 
				    dataType:'json',
				    data : {
			        	pkId : ids.toString()
			        },
				    success : function(response){
				    	$('#myModalUpdate').modal();
				    	//将显示的进行显示
				    	//默认id
				    	$("#myModalUpdate input[name='pkId']").val(ids.toString());
				    	$("#myModalUpdate input[name='clientName']").val(response.clientName);
				    	$("#myModalUpdate input[name='clientId']").val(response.clientId);
				    	$("#myModalUpdate input[name='operationName']").val(response.operationName);
				    	$("#myModalUpdate input[name='operationId']").val(response.operationId);
				    	$("#myModalUpdate input[name='equipId']").val(response.equipmentId);
				    	$("#myModalUpdate input[name='equipCode']").val(response.equipCode);
				    	$("#myModalUpdate input[name='equipName']").val(response.equipName);
				    	$("#myModalUpdate input[name='address']").val(response.communicateAddr);
				    	$("#myModalUpdate input[name='frequency']").val(response.frequency);
				    	$("#myModalUpdate input[name='remark']").val(response.remark);
				    	
				    	//选中的进行选中
//				    	$("#myModalUpdate .clientCodeConnect").find("option[value='"+response.clientId+"']").attr("selected",true);
				    	
				    	$("#myModalUpdate .type").find("option[value='"+response.type+"']").attr("selected",true);
				    	
				    	/*$("#myModal .equipCodeConnect").select2({
				    		 placeholder: response.equipCode,
				    	});*/ 
				    	
				    
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	console.log(data);
				    	alert("系统错误");
				    }
				});
				
				
				
				
				
				
				
				
				
				
				
				/*var ids = $.map($('#connectEquipmentTable').bootstrapTable('getSelections'), function (row) {
			        return row.pkId;
			    });
				
				var equipCodes = $.map($('#connectEquipmentTable').bootstrapTable('getSelections'), function (row) {
			        return row.equipCode;
			    });
				var operationIds = $.map($('#connectEquipmentTable').bootstrapTable('getSelections'), function (row) {
			        return row.operationId;
			    });
			    if (ids.length != 1 ) {
			    	DialogUtil.warning("请选择一行修改");
			        return;
			    }
			    //初始化用户角色
			    $("#myModal .clientCodeConnect").empty();
			    
			    $("#myModal .equipCodeConnect").empty();
			    //获取连接设备编号--加上工序的过滤
			    ConnectEquipmentInit.getQueryEquipment(operationIds.toString());
			    ConnectEquipmentInit.getCollect();
			    $("#myModal .yes").attr("disabled",false);
			    
			    //修改相关信息
			    
			    setTimeout(function timeOut(){
				$.ajax({
					url: ctx +'/equipment/connect/getEquipmentCollectById/get.mvc',
				    type:"post", 
				    dataType:'json',
				    data : {
			        	pkId : ids.toString()
			        },
				    success : function(response){
				    	$('#myModal').modal();
				    	//将显示的进行显示
				    	//默认id
				    	$("#myModal input[name='pkId']").val(ids.toString());
				    	$("#myModal input[name='clientName']").val(response.clientName);
				    	$("#myModal input[name='operationName']").val(response.operationName);
				    	$("#myModal input[name='operationId']").val(response.operationId);
				    	$("#myModal input[name='equipId']").val(response.equipmentId);
				    	$("#myModal input[name='equipName']").val(response.equipName);
				    	$("#myModal input[name='address']").val(response.communicateAddr);
				    	$("#myModal input[name='frequency']").val(response.frequency);
				    	$("#myModal input[name='remark']").val(response.remark);
				    	
				    	//选中的进行选中
				    	$("#myModal .clientCodeConnect").find("option[value='"+response.clientId+"']").attr("selected",true);
				    	
				    	$("#myModal .type").find("option[value='"+response.type+"']").attr("selected",true);
				    	
				    	$("#myModal .equipCodeConnect").select2({
				    		 placeholder: response.equipCode,
				    	}); 
				    	
				    
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	console.log(data);
				    	alert("系统错误");
				    }
				});
			    },1000);*/
			    /*$("#myModal input[name='clientName']").attr("disabled",true);
				$("#myModal input[name='operationName']").attr("disabled",true);
				$("#myModal input[name='equipName']").attr("disabled",true);
				$("#myModal input[name='communicateInter']").attr("disabled",true);
				$("#myModal .clientCodeConnect").attr("disabled","disabled");
				$("#myModal .equipCodeConnect").attr("disabled","disabled");*/
			});
			
			//新增用户-确定
			$("#myModalUpdate .yes").on(
					"click",
					function() {
//						$("#myModal input[name='clientName']").attr("disabled",false);
//						$("#myModal input[name='operationName']").attr("disabled",false);
//						$("#myModal input[name='equipName']").attr("disabled",false);
//						$("#myModal input[name='communicateInter']").attr("disabled",false);
						$("#myModalUpdate").data("bootstrapValidator").validate();
						var flag = $("#myModalUpdate").data("bootstrapValidator").isValid();
						if(!flag){
							//未通过验证
							return false;
						}
						
						/*$("#myModal .clientCodeConnect").removeAttr("disabled");
						$("#myModal .equipCodeConnect").removeAttr("disabled");
						if ($('.equipCodeConnect').select2('val') != null) {
							$("#myModal input[name='equipCode']").val($('.equipCodeConnect').select2('val'));
						}*/
						// $("#myModalUpdate .yes").attr("disabled",true);
						$.ajax({
							url : ctx + '/equipment/connect/saveEquipmentConnect/save.mvc',
							type : "post",
							dataType : 'json',
							data : $("#updateForm").serialize(),
							success : function(response) {
								
								if (response.result == true) {
									DialogUtil.ok("保存成功");
									//取消
									$('#myModalUpdate').modal('hide');
									$('#connectEquipmentTable').bootstrapTable('refresh');
								}
								if (response.result == false ) {
									DialogUtil.warning(response.message);
									// $("#myModalUpdate .yes").attr("disabled",false);
								}
								
							},
							error : function(XMLHttpRequest, textStatus, errorThrown) {
								alert("系统错误");
							}
						});
						return false;
					});
		},
		//获取连接设备编号--加上工序的过滤
		getQueryEquipment : function(value){
			$('.equipCodeConnect').select2({
				  ajax: {
				    url: ctx +'/equipment/register/listAllEquipmentByOperationId/get.mvc',
				    dataType: 'json',
				    data: function (params) {
				        var query = {
				          search: params.term,
				          page: params.page || 1,
				          operationId : value
				        };
				        return query;
				    },
				    processResults: function (data) {
				    	var equipArr =new Array();
				    	for ( var i = 0; i < data.length; i++) {
							var obj=new Object();
							obj.id=data[i].equipCode;
							obj.text=data[i].equipCode;
							equipArr.push(obj);
						}
				    	var result = {
				    		results: equipArr
				    	};
				        return result;
				      },
				      cache: true
				  },
				  placeholder: '请选择',
				  language: "zh-CN",
				  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
				  minimumInputLength: 0,
			});
			
		},
		//改变设备编号触发的事件
		changeEquipment : function(){
			$(".equipCodeConnect").on("select2:select",function(){  
				$.ajax({
					url: ctx +'/equipment/register/getEquipmentByEquipCode/get.mvc',
				    type:"post", 
				    dataType:'json',
				    data: {
				    	equipCode : $(".equipCodeConnect").val()
				    },
				    success : function(data){
				    	console.log(data);
				    	$("#myModal input[name='equipId']").val(data.pkId);
				    	$("#myModal input[name='equipName']").val(data.equipName);
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	alert("系统错误");
				    }
				});
	        }); 
		},
		//获取采集终端信息
		getCollect : function(){
			$.ajax({
				url: ctx +'/equipment/terminal/listAllCollectTerminal/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : '',
			    success : function(data){
		    		for (var i = 0; i < data.length; i++) {
		    			console.log(data[i].clientCode);
			    		 $("#myModal .clientCodeConnect").append("<option value='"+data[i].pkId+"'  >" + data[i].clientCode + "</option>");
			    	 };
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
			var value = $("#myModal input[name='operationId']").val();
			ConnectEquipmentInit.getQueryEquipment(value);
		},
		//通过采集终端编号获取对应的采集终端的信息
		changeCollect : function(){
			$(".clientCodeConnect").on("change","",function(){
				$("#myModal .equipCodeConnect").empty();
				$("#myModal .equipCodeConnect").append('<option value="">请选择</option>');
				$("#myModal input[name='equipName']").val("");
		    	$("#myModal input[name='communicateInter']").val("");
				$.ajax({
					url: ctx +'/equipment/terminal/getCollectTerminalById/get.mvc',
				    type:"post", 
				    dataType:'json',
				    data: {
				    	pkId : $(".clientCodeConnect").val()
				    },
				    success : function(data){
				    	$("#myModal input[name='clientName']").val(data.clientName);
				    	$("#myModal input[name='operationName']").val(data.operationName);
				    	$("#myModal input[name='operationId']").val(data.operationId);
				    	var value = $("#myModal input[name='operationId']").val();
						ConnectEquipmentInit.getQueryEquipment(value);
				    },
				    error: function(XMLHttpRequest, textStatus, errorThrown){
				    	alert("系统错误");
				    }
				});
				
			});
		},
		
	};
}();
 
jQuery(document).ready(function() {
	//1.初始化Table
    var oTable = new ConnectEquipmentTableInit();
    oTable.Init();
    //初始化页面
    ConnectEquipmentInit.init();
});

